#ifndef HTTP_RESPONSE_H
#define HTTP_RESPONSE_H
#include <QByteArray>

#include <map>
#include <string>
#include <QMap>

class HttpResponse
{
public:
    enum HttpStatusCode {
        kUnknown,
        k200Ok = 200,
        k400BadRequest = 400,
        k403Forbidden = 403,
        k404NotFound = 404,
    };

    explicit HttpResponse(bool close = false);

    // 设置响应状态码
    void setStatusCode(HttpStatusCode code) {m_statusCode = code;}
    void setStatusMessage(const QByteArray &message) {m_statusMessage = message;}
    // 设置是否支持XMLHttpRequest的CORS
    void setCorsStatus(bool status) {m_corsStatus = status;}
    // 返回是否支持XMLHttpRequest的CORS的状态
    bool corsStatus() const {return m_corsStatus;}
    // 设置是否保持连接
    void setCloseConnection(bool on) {m_closeConnection = on;}
    bool closeConnection() const {return m_closeConnection;}
    // 设置Content-Type
    void setContentType(const QByteArray &contentType) {addHeader("Content-Type", contentType);}
    // 添加头部字段
    void addHeader(const QByteArray &key, const QByteArray &value) {m_headers[key] = value;}
    // 设置body数据
    void setBody(const QByteArray &body) {m_body = body;}
    //输出HTTP响应数据到output
    void appendToBuffer(QByteArray &output) const;

    //构造一个文本类型的HTTP响应报文
    static QByteArray makeTextResponse(HttpStatusCode code, const QByteArray &message, bool closeStatus = true);
    // 构造一个json类型的HTTP响应报文
    static QByteArray makeJsonResponse(HttpStatusCode code, const QByteArray &message, bool closeStatus = true);
    // 构造一个 404 Not Found 页面
    static QByteArray makeNotFoundResponse();
    // 状态码转换为可读的字符串
    static QString statusCodeToString(HttpStatusCode statusCode);

private:
    QMap<QByteArray, QByteArray> m_headers; //请求头部
    HttpStatusCode m_statusCode; //状态码
    QByteArray m_statusMessage; //HTTP状态描述短语
    bool m_closeConnection; //HTTP是否保持长连接
    QByteArray m_body; // HTTP的消息体部分
    bool m_corsStatus; //支持 XMLHttpRequest的CORS, 默认为true
};


#endif // HTTP_RESPONSE_H
